package com.tomcat;

import com.sun.jndi.toolkit.url.Uri;
import com.tomcat.annotation.WebServlet;
import com.tomcat.exception.UriUnuniqueException;

import java.io.File;
import java.net.URL;
import java.util.HashMap;

public class TomcatWebServletScan {

    public HashMap<String, HttpServlet> servletScan() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
HashMap<String,HttpServlet> servletHashMap=new HashMap<>();
String basePackage="com.tomcat.test";
        String path = basePackage.replaceAll("\\.", "/");
        URL url = TomcatWebServletScan.class.getResource("/");
        File file=new File(url.getFile()+path);
        File[] files = file.listFiles();

        for (int i = 0,len=files.length; i < len; i++) {
            if (files[i].isFile()){
                String fileName = files[i].getName();
                if (fileName.endsWith(".class")){
                    String[] strings = fileName.split("\\.");
                   String className= strings[0];
                  String allName= basePackage+"."+className;
                    Class<?> aClass = Class.forName(allName);
                    WebServlet annotation = aClass.getAnnotation(WebServlet.class);
                    if (annotation!=null){
                        String value = annotation.value();
                        if (servletHashMap.get(value)!=null){
                            throw new UriUnuniqueException("出现两个一样的地址："+value);

                        }
                        HttpServlet servlet= (HttpServlet) aClass.newInstance();
                        servletHashMap.put(value,servlet);
                    }
                }


            }
        }

        return servletHashMap;
    }

}
